<?php


// WHAT A FUCKING FUCKING HACK!!!

	include_once("cmsConfig.php");// this should have already been included..


	/**
	 * This is a simple helper for displaying validation errors
	 *
	 * @param string $message
	 * @param string $element
	 */
	function validationMessage($message, $element){
		if (!is_null($message) && $err=$message->getMessageForKey($element->name) ) {
			print( '<br/><span class="cms_error">' . $element->label .' '. $err .'</span>');//
		} 				
	}
	
	//things needed over the entire run of the script...
	$authInfo = extractObjectWithKeyFromArray('authInfo', $_SESSION);
	$message = null;
	$canDoForm = true;
	
	//declare these now just in case.
	$documentCodeSave = null;
	$formId = extractNumberWithKeyFromArray('formId', $_REQUEST, null);
	$documentCode = extractNumberWithKeyFromArray('documentCode', $_REQUEST, null);
	
	$documentContent = null;// we dont want this to clobber existing values..	
	
	// what operation are we doing... saving
	$processFormData = extractStringWithKeyFromArray("processFormData", $_REQUEST, "NO");
	$processFormData = $processFormData == "YES";
	
	//or relicating..
	$replicateDocument = extractStringWithKeyFromArray("replicateDocument", $_REQUEST, "NO");
	$replicateDocument = $replicateDocument == "YES";
	
	//get the passed in return url, and set it in the session.
	$returnURL = extractStringWithKeyFromArray('returnURL', $_REQUEST);
	if (!is_null($returnURL)) {
		$_SESSION['returnURL'] = $returnURL;
	}
		
	//this will be okay here.. as it should be clobbered.. by other
	//values
	
	// this tends to clobber the passed in document code..
	// we only want to suck this in.. if we have not got one passed in...
	if (is_null($formId) && is_null($documentCode)){
		$formIdSave = extractNumberWithKeyFromArray('formIdSave', $_SESSION, null);
		if ( !is_null($formIdSave)){
			$_REQUEST['formId'] = $formIdSave;//vape this if we have something passed in.
		}
	} else {
		$formIdSave = $formId;
		$_SESSION['formIdSave'] = $formIdSave;
	}
	
	if (is_null($documentCode) && is_null($formId)){//both of these musy be null
		$documentCodeSave = extractNumberWithKeyFromArray('documentCodeSave', $_SESSION, null);
		if (!is_null($documentCodeSave)){
			$_REQUEST['doucmentCode'] = $documentCodeSave;
		}
	} else {
		$documentCodeSave = $documentCode;
		$_SESSION['documentCodeSave'] = $documentCodeSave;
	}
	
	if ($replicateDocument) {//
		$replicatecode = extractNumberWithKeyFromArray("replicatecode", $_REQUEST, null);
		if (!is_null($replicatecode)) {
			//pull ot the replicate foo.. replicate and then fiddle around for editing.. not adding.. 
			$cmsReplicator = new CmsReplicator($replicatecode, $authInfo, $db);
			$replication = $cmsReplicator->replicate();
			$documentContent = &$replication;
		}
	//	
	//	//we then need to merge the replication in some how..to the existing content..
	//	
	} else // we can replicate or process but not both..//
	if ($processFormData) {
		
		include_once("lib/CmsWriter.php");

		$cmsWriter = new CmsWriter( $formIdSave, $documentCodeSave, $_POST, $authInfo, $db);
		$message = $cmsWriter->processFormData();
		$documentContent = $cmsWriter->formData;
		
		$canDoForm = $message->hasErrors;// if we have errors, we can do the form..
		//myPrintR($message);
		//we have no errors, we can display a dialog...
		if( ! $message->hasErrors){


			//get the return url from the session..
			
			$returnURL= extractStringWithKeyFromArray('returnURL', $_SESSION, null);
			
			if (is_null($returnURL)) {
				//once we get this far, we need to strip/ clear the form/document stuff from the session..
				$returnURL = CMS_HOME . "?fileNo=1&formid=" . $formIdSave;
			}
			//possibly dont need those...
			unset($_SESSION['formIdSave']);
			unset($_SESSION['documentCodeSave']);
			unset($_SESSION['returnURL']);
				
			$documentType = getDocumentTypeForDocumentTypeCode($cmsWriter->formData['documenttypecode'], $db);
			
			$message->addValidationMessageForKey("CmsWrite","db_OBJECT_SAVED",CMS_STATUS_NOTICE);
			$m = "The '" . $documentType->documenttypedescription . "' with code ". $cmsWriter->documentCode . " was saved successfully.";
			
  			dialoguePage(array(	DLG_MESSAGE=> 	$m,
						DLG_LEFT_TEXT=>	DLG_EMPTY,
						DLG_LEFT_LINK=>	CMS_HOME,
						DLG_RIGHT_TEXT=>	DLG_OK,
						DLG_RIGHT_LINK=>	urldecode($returnURL) ));			
		}
	}
	

	
	
	
	if ($canDoForm) { // can do form --

		//	//$actionUrl = "/cms/html/index.php?fileNo=3";//these should be perhaps stored in a session.. yes no maybe..

		$tableWriter = new CmsTableWriter(CMS_FORMAT, $db);
		$cmscontentmetadataTableWriter = new CmsTableWriter("cmscontentmetadata", $db);
		$formDescriptor = new CmsTableWriter(CMS_FORM_DESC_FORMAT,$db);	

		//mangle to ensure unset things are not passed through..
		if (is_null($documentCode))
			$documentCode = extractNumberWithKeyFromArray('documentCode', $_REQUEST);
			
		if (is_null($formId))
			$formId = extractNumberWithKeyFromArray('formId', $_REQUEST);

		$formDescription = null;

		// this block is for displaying status etc when the form is first loaded..
		// -- BEGIN FORM LOAD ERRORS -- // -- 
		if ( (is_null($documentCode) && is_null($formId)) ) {
			//it does not matter at this point if we have both.
			// as if there is a document code.. the formid will be overwritten..
				
				dialoguePage(array(	DLG_MESSAGE=>		"ILLEGAL STATE, you must specify either a formId to add or a documentCode to edit",
						DLG_LEFT_TEXT=>		DLG_EMPTY,
						DLG_LEFT_LINK=>		CMS_HOME,
						DLG_RIGHT_TEXT=>	DLG_OK,
						DLG_RIGHT_LINK=>	CMS_HOME ));

		} else if (is_numeric($documentCode ) && $documentCode > 0 ) {
			//echo "editing";
		
			//not sure about this.. will need to figure out what it is used for.
			$actualContent = $tableWriter->readItem($documentCode);
			$cmscontentmetadata = $cmscontentmetadataTableWriter->readItem($documentCode);
			//if we have a processed form.. we need to get its content.
			//and not the content we have just read in..
			if (is_null($documentContent)){
				$documentContent = &$actualContent;
			}
			
			
			if(($actualContent === false)){
				dialoguePage(array(	DLG_MESSAGE=>		"You have specified an invalid document code",
						DLG_LEFT_TEXT=>		DLG_EMPTY,
						DLG_LEFT_LINK=>		CMS_HOME,
						DLG_RIGHT_TEXT=>	DLG_OK,
						DLG_RIGHT_LINK=>	CMS_HOME ));

			// we then look up the form that the document/content was created against
			} else if (!($formDescription = $formDescriptor->readItem($actualContent->formid))){
				dialoguePage(array(	DLG_MESSAGE=> 		"You have requested an non existant CMS form",
						DLG_LEFT_TEXT=>		DLG_EMPTY,
						DLG_LEFT_LINK=>		CMS_HOME,
						DLG_RIGHT_TEXT=>	DLG_OK,
						DLG_RIGHT_LINK=>	CMS_HOME ));
	
			//we then check to see if we are infact allowed to edit this content..
			} else if (!editFormAuth($authInfo, $formDescription, null, $db)){		
				dialoguePage(array(	DLG_MESSAGE=>		"You are not allowed to edit the requested content",
						DLG_LEFT_TEXT=>		DLG_EMPTY,
						DLG_LEFT_LINK=>		CMS_HOME,
						DLG_RIGHT_TEXT=>	DLG_OK,
						DLG_RIGHT_LINK=>	CMS_HOME ));
			} else {
				$formIdSave = $formDescription->formid;			
			}
		// we only need to do the form description if we are adding a new item
		} else	if (is_numeric($formId ) && $formId > 0 ) {
	
			if (!($formDescription = $formDescriptor->readItem($formId))){

				dialoguePage(array(	DLG_MESSAGE=> 		"You have requested an non existant CMS form",
						DLG_LEFT_TEXT=>		DLG_EMPTY,
						DLG_LEFT_LINK=>		CMS_HOME,
						DLG_RIGHT_TEXT=>	DLG_OK,
						DLG_RIGHT_LINK=>	CMS_HOME ));
							
			} else if (!addFormAuth($authInfo, $formDescription, null, $db)){
		
				dialoguePage(array(	DLG_MESSAGE=>		"You are not allowed to access this CMS form",
						DLG_LEFT_TEXT=>		DLG_EMPTY,
						DLG_LEFT_LINK=>		CMS_HOME,
						DLG_RIGHT_TEXT=>	DLG_OK,
						DLG_RIGHT_LINK=>	CMS_HOME ));
			} else {
				$formIdSave = $formId;
			}
		
		}// else
		 

		//finally???
		if ($formIdSave > 0){
			$element = new CmsFormElement($formDescription, $db);
			
			
			//do an ookey merge here? we need to get any posted in args  merge in with the content.. not
			// too sure if this is the best place...  or somewhere else.
			// we need to set the content.. depending on what way we got here..
			$element->setContent($documentContent);
		}
		
		// -- END FORM DISPLAY/LOAD ERRORS //
	

//		we need a form description and an element here.. the rest can be then worked out.
		if ( $formIdSave>0 && instanceOf($formDescription, 'stdClass') && instanceOf($element, 'cmsformelement') ) {
	
			if (!is_null($formIdSave))
				$_SESSION['formIdSave'] = $formIdSave;
			
			if (!is_null($documentCode))
				$_SESSION['documentCodeSave'] = $documentCode;	
		
			$editMode = "Edit";
			if (is_null($documentCode)) { $editMode = "Add"; }

			
?>
<div class="cms_browse_heading">
	<div class="cms_browse_heading_label">
		<h1><?= $formDescription->formname ?></h1>
	</div>
	<div class="cms_browse_addrecord"></div>
</div>
<div id="cms_browse_topdivider" class="cms_browse_divider"></div>	
<?
	if (false  && is_null($documentCode) ) {
?>
<FORM <?= $_SERVER['PHP_SELF']?>" name="cms_replicate_form" id="cms_replicate_form" method="POST">
	<INPUT type="hidden" value="YES" name="replicateDocument" />
	<div class="cms_form_replicate">
Replicate Existing:
<?
	// we need to add a drop down here of the documents of this type, with their name and codes..
	
	optionList(
		array(
			"name"=>"replicatecode",
			"id"=>"cms_form_replicate_codes",
			"class"=>"cms_form_replicate"
		),
		false,
		null,
		0,
		1,
		"SELECT documentcode, CONCAT(documentcode,' - ',title) FROM content WHERE formid='$formDescription->formid' ORDER BY documentcode",
		$db
	);
?><input type="image" id="cms_form_replicate_action" class="cms_form_replicate" src="/cms/images/button_go.gif" />
</div>
</FORM>	
<?
	}
?>
		  <form
		  	class="cms_form" action="<?= $_SERVER['PHP_SELF'] ?>" 
		  	method="post" enctype="multipart/form-data"
		  	name="<? print($formDescription->formname); ?>" 
		  	id="<? print($formDescription->formname); ?>"
		  >
		  
			<input type="hidden" name="processFormData" value="YES" />

<div class="cms_masteredit">
  	<table width="100%" border="0" cellspacing="0" cellpadding="0" class="cms_masteraddedit_table" >
	  	<tr>
	  		<td height="1" width="160"><img src="/cms/images/spacer.gif" height="1" width="160" /></td>
	  		<td height="1"><img src="/cms/images/spacer.gif" height="1" width="1" /></td>
		</tr>
		<tr class="cms_masteraddedit_table">
		  <td class="cms_form_label">List Label:</td>
		  <td class="cms_form_element">
		    <input type="text" name="metadata_label" value="<? if (isset($cmscontentmetadata->label)) echo magicClean($cmscontentmetadata->label); ?>" class="cms_form_text" maxlength="32">
		  </td>
		</tr>
		<tr class="cms_masteraddedit_table">
		  <td class="cms_form_label">Rank:</td>
		  <td class="cms_form_element">
		    <input type="text" name="metadata_rank" value="<? if (isset($cmscontentmetadata->rank)) echo $cmscontentmetadata->rank; ?>" class="cms_form_text">
		  </td>
		</tr>
<?
	foreach ($formDescription as $fieldName => $field){
			
				$e = $element->getElementDescriptor($field);
				//myPrintR($e);

//				myPrintR($field);
				//				
				$rowId = "cms_masteredit_" . $element->formId . "_" . $e->elementid;
				
//				echo $fieldName ."-" .$e->name ." <br />";
				if ( !(	$fieldName == 'formid' ||
					$fieldName == 'formname' ||
					$fieldName == 'usertype' ||
					$fieldName == 'editmode' || 
					$fieldName == 'uid' ||
					$fieldName == 'gid' ||
					$fieldName == 'permission' ||
					$fieldName == 'sidebarmodule' ||				
					$fieldName == 'activemodule' ||				
					$fieldName == 'contentmodule' ||				
					$fieldName == 'modeaccess' ||
//					$fieldName == 'intranetmodule' ||		
					$e->elementtype == CMS_ELEMENT_HIDDEN )
			
				//|| $e->
				) {

					
					// see if anything has already been bunged in on the request?
					// if we have something posted in..
					// but.. it is not in the content.. add it here to the content..
					// this only really applies when adding and we want to pass in a default.
					if (is_null($documentCode)) {
						$requestValue = null;
						$requestValue = extractValueWithKeyFromArray( $e->name, $_REQUEST,null );
						if ( is_null($element->content)) {
							$element->content = new stdClass();
						}
						if (!is_null($requestValue) && !isset($element->content->{ $e->name }) ) {
							$element->content->{ $e->name } = $requestValue; 							
						}
					}
					if( $e->elementtype == CMS_ELEMENT_FCKEDIT_TEXT || $e->elementtype == CMS_ELEMENT_TINYMCE_TEXT) {
?>
		<tr  id="<?= $rowId ?>_label"> 
			<td  colspan="2" class="cms_form_label" id="cms_form_label_<?= $e->name ?>"><?= $e->label ?></td>
		</tr>
		<tr id="<?= $rowId ?>_editor" class="cms_masteraddedit_table">
			<td  class="cms_form_element" colspan="2"><? $element->printElement($field); validationMessage( $message, $e);?></td>
		</tr>
<?
					} else {
?>
		<tr id="<?= $rowId ?>" class="cms_masteraddedit_table"> 
	  		<td id="cms_form_label_<?= $e->name ?>" class="cms_form_label" ><?= $e->label ?></td> 
            <td class="cms_form_element" align="left">
		
<?
		$element->printElement($field); validationMessage( $message, $e);
?>
			</td>
		</tr>
<?
					} 
				}		
			}


	// add stuff for site selection here.. if the user has no sites.. really, this form should not show up.. but that is an other story..
	if ( CMS_ENABLE_SITE_CONTENT ){
		// we need to get the users um things.. sites first.. 
		
		//		
		//gort.. we need to fiddle this so that if there is only one site in the form.. that it is alloed to be in.
		//
		// that 
		
		//we take the mode access.. and bust out the seperate modes,, magical factorage
		//myPrintR($formDescriptor);
		$formModes = array();		
		for ($b = 1; $b <= $formDescription->modeaccess ;  ){
			$mode = ($b) & $formDescription->modeaccess;
			//echo $mode . "<br/>";
			if ( $mode > 0 )
				array_push($formModes, $mode);
			$b = $b << 1;
		}
		
		//now .. if we have more than one site group in the form .. then we need to do 
		// all the site selector..
		// otherwise we default to the only specified / allowed site..

			$userSites = getSiteModesForUser($authInfo->uid, $db);
			$newUserSites = array();
			foreach ($formModes as $formMode) {
				foreach ($userSites as $userSite) {
					if ($userSite->modemask == $formMode) {
						array_push($newUserSites, $userSite);
					}
				}
			} 
		// myPrintR($userSites,"userStes");
			$userSites = $newUserSites;
			
			//myPrintR($userSites,"userStes");
			

			
		//	myPrintR($userSites,"userStes");
		//	myPrintR($contentSites,"contentSites");
		//	myPrintR($formModes);

			if (count($userSites) > 1) {
			
			//this pulls out the list of the sites that are set in the content..
	 		$allContentSites = $db->getAllAsObjects("SELECT t1.* FROM grouplist AS t1,sitecontent AS t2 WHERE t1.gid = t2.sitegroupid AND t2.documentcode=? ", ($a = array($documentCode )) );		
			
			$contentSites = array_intersect($allContentSites,$userSites);
			
			$excludedSites = array();

			$userSites = array_values($userSites);
			

			foreach ($allContentSites as $csk => $csv) {
				$exclude = true;	
				foreach ($userSites as $usk => $usv){
					if ($csv->gid == $usv->gid){
						$exclude = false;
					}
				}
				if ($exclude){
					array_push($excludedSites, $csv->groupname);
					$exclude=true;
				}
			}
			
		print <<< EOD
		<tr id="siteContent" > 
			<td id="siteContent_label" class="cms_form_label">Site Publishing:</td>
			<td id="siteContent_form_elemnt" class="cms_form_element">
EOD;
				$opts = array();
				$opts["descriptionStringKeyPath"] = "groupname";
				$opts["valueKeyPath"] = "gid";
				printDualCheckBoxList("sites",$userSites, $contentSites, ($opts) ) ;
				if (0 < count($excludedSites)) {
					echo "<div style=\"clear: both\"><br/>Excluded Sites: " . implode(", ",$excludedSites) . " </div>";
				}
		print <<< EOD
			</td>
		</tr>
EOD;
			} else { }			

	}

	//if the permissions system is turned on.. show the selector here???
	// add bollocks here for permissions..
	
	if (CMS_ENABLE_USER_PERMISSIONS) {
		// i will make this more advanced later.. so that users can alter permissions if they have the pbit set or something like that..
		//but for now we will just add it here
		$gid= extractNumberWithKeyFromArray('gid',$_REQUEST, null);
		if ($formDescription->displaygroup) {
			
		
			if ($authInfo->usertype != CMS_USERTYPE_SU ) {
				$groups = groupsForUserId($authInfo->uid, $db);
				$q = "SELECT gid, groupname FROM grouplist WHERE gid IN (" . implode(',', $groups ) . ") ORDER BY gid";
			} else {
				$q = "SELECT gid, groupname FROM grouplist  ORDER BY gid";			
			}
			
			//get the groups here....
			$db->executeQuery($q);
			
			echo "<tr>\n<td><b>Group:</b></td>\n<td>";
			echo "<select name=\"gid\" >\n<option  value=\"" . 0 . "\">-</option>\n";
			while ($row = $db->nextObject()) {
				if ($row->gid == $gid || $row->gid == $actualContent->gid) {
					$selected = "selected=\"yes\""; 
				} else { 
					$selected = "";
				}
				echo "<option ". $selected ." value=\"" . $row->gid . "\">" . $row->groupname . "</option>\n";
			}
		
			echo "</select>\n</td>\n</tr>\n";
		} else {
		
			if (!is_null($gid)) {
				echo "<input type=\"hidden\" value=\"$gid\" name=\"gid\" />";
				
			}
		}
	}
			
?>
		<tr>   
			<td colspan="2" align="right" valign="middle">
<?
	$js = <<< EOD
<script language="javascript" type="text/javascript">
	function selectAllElementsInSelect( select ) {
		for (i=0; i < select.options.length; i++){
			select.options[i].selected = true;
		}
		return;
	}
	
	function doOnSubmitForElementsOnForm( formName ){
		f = document.getElementById( formName );
		if (f != null){

			for (j = 0; j < f.length; j++ ){
				e =  f[j];				
				if (e.onsubmit){
					e.onsubmit();
				}
			}
		}
		return;
	}
</script>
EOD;
echo preg_replace('/[\r\n\t ]+/',' ', $js);
//echo $js;
?>
	            <a id="cms_form_submit_<?= $formDescription->formid ?>" class="cms_form_submit" href="javascript:doOnSubmitForElementsOnForm('<?= $formDescription->formname ?>');document.forms['<?= $formDescription->formname ?>'].submit();" ><img src="/cms/images/button_go.gif" /></a>
			</td>
		</tr>
	</table>
</form>
</div>

<?php
			}
		
}
?>